# -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in root directory
##############################################################################
from openerp import models, fields, api
import re
BASE_LOCATION= {
    'production':7,
    'scrapped': 4,
    'stock': 12,
}

class QcInspection(models.Model):
    _inherit = 'qc.inspection'

    @api.one
    @api.depends('object_id')
    def get_production(self):
        self.production = False
        if self.object_id:
            if self.object_id._name == 'stock.move':
                self.production = self.object_id.production_id

    production = fields.Many2one(
        comodel_name="mrp.production", compute="get_production", store=True)

    @api.multi
    def split_product_by_level(self):
        """
        根据测试结果重新拆分产品
        """
        for inspection in self:
            if inspection.test.category.name==u'产品级别控制' and inspection.production:
                stock_move_obj = self.env['stock.move']
                production = inspection.production
                # 成品库位
                location_current =  inspection.production.location_dest_id
                uom_qty_all = inspection.production.product_qty
                product_id = inspection.production.product_id
                uom_id = product_id.uom_id
                # 生产库位
                production_location_id = product_id.property_stock_production.id
                # 待处理库位
                wait_location_id = BASE_LOCATION['stock']

                if product_id.product_tmpl_id.property_stock_finished:
                    wait_location_id = product_id.product_tmpl_id.property_stock_finished.id
                data_move = {
                    'name': u'质检重新分级产品',
                    'date': fields.datetime.now(),
                    'product_id': product_id.id,
                    'product_uom': uom_id.id,
                    'product_uom_qty': uom_qty_all,
                    'location_id': location_current.id,
                    'location_dest_id': BASE_LOCATION['production'],
                    'company_id': production.company_id.id,
                    'production_id': production.id,
                    'origin': production.name,
                }
                for line in inspection.inspection_lines:
                    uos_id = line.uom_id and line.uom_id or product_id.uos_id or product_id.uom_id
                    uos_qty = line.quantitative_value
                    uom_qty = uom_id._compute_qty(uos_id.id, uos_qty, uom_id.id)

                    #this is not necessary
                    #
                    # lwh = re.findall(r'\d+',uos_id.spec_name)
                    # if len(lwh)==3 and uos_qty!=0:
                    #     uom_qty =   1/uos_qty * int(lwh[0]) * int(lwh[1]) * int(lwh[2]) * 0.000000001
                    # else:
                    #     uom_qty = uom_id._compute_qty(uos_id.id, uos_qty, uom_id.id)
                    # print('2222222222222222',uom_qty)
                    if line.test_line.to_location_id and not line.test_line.src_location_id and uom_qty!=0:
                        """
                        从成品库位移至目标库位 (废品库)
                        """
                        data_move_to = data_move.copy()
                        data_move_to.update({
                            'name': u'废品',
                            'product_uom_qty': uom_qty,
                            'location_dest_id':line.test_line.to_location_id.id,
                        })
                        move_id =stock_move_obj.create(data_move_to)
                        move_id.action_confirm()
                        move_id.action_done()
                        uom_qty_all -= uom_qty
                    elif not line.test_line.to_location_id and line.test_line.src_location_id and uom_qty!=0:
                        """
                        生产成品
                        """
                        # 创建新产品
                        new_product = product_id.search_or_create_level(line.test_line.name)
                        # 生成产品

                        data_move_produce = data_move.copy()
                        data_move_produce.update({
                            'name': u'质检分级<%s>: %s' % (line.test_line.name,new_product.name),
                            'product_uom_qty': uom_qty,
                            'product_id': new_product.id,
                            'location_id':line.test_line.src_location_id.id,
                            'location_dest_id':wait_location_id,
                        })

                        move_id =stock_move_obj.create(data_move_produce)
                        move_id.action_confirm()
                        move_id.action_done()

                        # 消耗产品
                        data_move_consume = data_move.copy()
                        data_move_consume.update({
                            'name': u'消耗原产品',
                            'product_uom_qty': uom_qty,
                            'location_id':location_current.id,
                            'location_dest_id':line.test_line.src_location_id.id
                        })
                        move_id =stock_move_obj.create(data_move_consume)
                        move_id.action_confirm()
                        move_id.action_done()
                        uom_qty_all -= uom_qty
                if uom_qty_all < 0:
                    raise Exception(u"请检查,所有产品数量小于转移数量")
                elif uom_qty_all > 0:
                    data_move_produce = data_move.copy()
                    data_move_produce.update({
                        'name': u'质检分级<%s>: %s' % (u'成品',product_id.name),
                        'product_uom_qty': uom_qty_all,
                        'product_id': product_id.id,
                        'location_id': location_current.id,
                        'location_dest_id':wait_location_id,
                    })
                    move_id =stock_move_obj.create(data_move_produce)
                    move_id.action_confirm()
                    move_id.action_done()

    @api.multi
    def transfer(self):
        """
        根据测试结果转移成品
        """
        for inspection in self:
            if inspection.test.category.name==u'库位控制':
                location_from =  inspection.production.location_dest_id
                location_to =  inspection.production.to_location_id
                qty_all = inspection.production.product_qty
                product_id = inspection.production.product_id
                uom_id = product_id.uom_id
                for line in inspection.inspection_lines:
                    if line.test_line.to_location_id and line.quantitative_value > 0:
                        qty = line.quantitative_value
                        product = line.product
                        uos_id = line.uom_id
                        if uos_id and uos_id.uom_type == 'bigger':
                            qty = qty * factor
                        if uos_id and uos_id.uom_type == 'smaller':
                            qty = qty / factor
                        line_location_to = line.test_line.to_location_id
                        qty_all -= qty
                        self.env['stock.move'].create({
                            'name': u'质检转移<%s>: %s' % (line.test_line.name,product.name),
                            'product_id': product.id,
                            'product_uom_qty': qty,
                            'product_uom': uom_id.id,
                            'location_id': location_from.id,
                            'location_dest_id': line_location_to.id})
                if qty_all < 0:
                    raise Exception(u"请检查,所有产品数量小于转移数量")
                elif location_from and location_to and product_id and uom_id and qty_all > 0:
                    self.env['stock.move'].create({
                        'name': u'质检转移: %s' % product_id.name,
                        'product_id': product_id.id,
                        'product_uom_qty': qty_all,
                        'product_uom': uom_id.id,
                        'location_id': location_from.id,
                        'location_dest_id': location_to.id})


class QcInspectionLine(models.Model):
    _inherit = 'qc.inspection.line'

    production = fields.Many2one(
        comodel_name="mrp.production", related="inspection_id.production",
        store=True, string="Production order")
